package com.yiwei.jmx.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.IdCardIndentityBean;
import com.yiwei.jmx.api.bean.UploadImgBean;
import com.yiwei.jmx.api.bean.UploadSubmitIdcardBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.IdCardBitmap;
import com.yiwei.jmx.util.DateTime;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.GlideRoundTransform;
import com.yiwei.jmx.util.ImageUtil;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.Spans;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.SelectMenuTipsDilaog;
import com.yiwei.jmx.view.SureIdcardIndentityDilaog;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-5.
 */

public class IdcardIdentityActivity extends BaseActivity {

    private static final int CAMERA_REQUEST_CODE = 2;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_front)
    ImageView imgFront;
    @BindView(R.id.btn_one_take)
    ImageView btnOneTake;
    @BindView(R.id.btn_one_retake)
    TextView btnOneRetake;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.btn_two_take)
    ImageView btnTwoTake;
    @BindView(R.id.btn_two_retake)
    TextView btnTwoRetake;
    @BindView(R.id.txt_name)
    EditText txtName;
    @BindView(R.id.txt_idcard_no)
    TextView txtIdcardNo;
    @BindView(R.id.btn_one_change)
    TextView btnOneChange;
    @BindView(R.id.layout_one)
    FrameLayout layoutOne;
    @BindView(R.id.txt_place)
    EditText txtPlace;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.btn_two_change)
    TextView btnTwoChange;
    @BindView(R.id.layout_two)
    FrameLayout layoutTwo;
    @BindView(R.id.img_people)
    ImageView imgPeople;
    @BindView(R.id.btn_three_take)
    ImageView btnThreeTake;
    @BindView(R.id.btn_three_retake)
    TextView btnThreeRetake;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.txt_tips)
    TextView txtTips;

    private Unbinder unbiner;
    private int takeType;
    private static final String DEFAULT_NAME1 = "front_image.jpg";
    private static final String DEFAULT_NAME2 = "back_image.jpg";
    private static final String DEFAULT_NAME3 = "people_image.jpg";
    private boolean frontIdentity;
    private boolean backIdentity;
    private File mTempCameraFile;
    private UploadSubmitIdcardBean newModel = new UploadSubmitIdcardBean();
    private GlideRoundTransform glideRoundTransform;
    private SelectMenuTipsDilaog selectMenuTipsDilaog;
    private SureIdcardIndentityDilaog sureIdentityDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_idcard_identity);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
//        EventBus.getDefault().register(this);

    }

    private void init() {
        txtTitle.setText("身份认证");
        Spanned txt_tips = Spans.with(this).font("身份证认证失败？", getResources().getDimensionPixelSize(R.dimen.x24), 0xff566F8E).
                font("请点击这里看看", getResources().getDimensionPixelSize(R.dimen.x24), 0xff0072FF).
                build();
        txtTips.setText(txt_tips);
        glideRoundTransform = new GlideRoundTransform(this, 5);
        glideRoundTransform.setExceptCorner(false, false, true, true);
        sureIdentityDialog = new SureIdcardIndentityDilaog(this);
        sureIdentityDialog.setOnChooseListener(new SureIdcardIndentityDilaog.OnChooseListener() {
            @Override
            public void onSuccess() {
                getSubmitidCard(newModel);
            }
        });
        selectMenuTipsDilaog = new SelectMenuTipsDilaog(this).setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
            @Override
            public void onLeft() {
                finish();
            }

            @Override
            public void onRight() {
                Util.startActivity(IdcardIdentityActivity.this, IdcardIdentityFailTipsActivity.class);
            }
        }).showTwoSelectData("主人", R.mipmap.img_idcard_fail_dialog, "只有通过实名认证才能借款，您确定要离开，还是遇到问题了？", "残忍离开", "遇到问题");
    }

    private void getIdentity(int paramInt) {
        String str = "";
        if (paramInt == 0) {
//            正面
            str = ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap, 100);
        } else if (paramInt == 1) {
//            反面
            str = ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap, 100);
        }
        getIdentityInfo(paramInt, str);
    }

    public void getUploadImage(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImage(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    newModel.setHand_image(result.getUrl());
                    Glide.with(this).load(result.getUrl()).into(imgPeople);
                    if (frontIdentity && backIdentity && !TextUtils.isEmpty(newModel.getHand_image())) {
                        btnSubmit.setSelected(true);
                    }
                });
    }

    public void getSubmitidCard(UploadSubmitIdcardBean item) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        Api.api_service.getSubmitidCard(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "认证成功");
                    Util.startActivity(this, FaceIdentityActivity.class);
                    finish();
                });
    }

    public void getIdentityInfo(int paramInt, String paramString) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        IdCardIndentityBean bean = new IdCardIndentityBean();
        bean.img = paramString;
        Api.api_service.getIdentityInfo(paramInt, bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(item -> {
                    if (item.getStatus() != 0) {
                        if (paramInt == 0) {
//       正面
                            if (TextUtils.isEmpty(item.getName()) || TextUtils.isEmpty(item.getGendor()) || TextUtils.isEmpty(item.getNation()) || TextUtils.isEmpty(item.getBirthday()) || TextUtils.isEmpty(item.getAddress()) || TextUtils.isEmpty(item.getIdno()) || TextUtils.isEmpty(item.getFront_image())) {
                                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_front)).show();
                                frontIdentity = false;
                                return;
                            }
                            frontIdentity = true;
                            newModel.setName(item.getName());
                            newModel.setFront_image(item.getFront_image());
                            newModel.setIdno(item.getIdno());
                            newModel.setBirthday(item.getBirthday());
                            newModel.setGendor(item.getGendor());
                            newModel.setAddress(item.getAddress());
                            newModel.setNation(item.getNation());
//                            imgFront.setImageBitmap(IdCardBitmap.bitmap);
                            txtName.setText(item.getName());
                            txtIdcardNo.setText(item.getIdno());
                            Glide.with(this).load(item.front_image).transform(glideRoundTransform).into(imgFront);
                            layoutOne.setVisibility(View.VISIBLE);


                            if (frontIdentity && backIdentity && !TextUtils.isEmpty(newModel.getHand_image())) {
                                btnSubmit.setSelected(true);
                            }
                        } else {
                            if (TextUtils.isEmpty(item.getIssue_by()) || TextUtils.isEmpty(item.getValid_start()) || TextUtils.isEmpty(item.getValid_end()) || TextUtils.isEmpty(item.getBack_image())) {
                                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_back)).show();
                                backIdentity = false;
                                return;
                            }
                            newModel.setValid_start(item.getValid_start());
                            newModel.setValid_end(item.getValid_end());
                            newModel.setBack_image(item.getBack_image());
                            newModel.setIssue_by(item.getIssue_by());
                            backIdentity = true;
                            layoutTwo.setVisibility(View.VISIBLE);
                            txtPlace.setText(item.getIssue_by());
                            txtTime.setText(item.getValid_start() + "-" + item.getValid_end());
//                            txtTime.setText();
                            Glide.with(this).load(item.back_image).transform(glideRoundTransform).into(imgBack);
                            if (frontIdentity && backIdentity && !TextUtils.isEmpty(newModel.getHand_image())) {
                                btnSubmit.setSelected(true);
                            }
//                            imgBack.setImageBitmap(IdCardBitmap.bitmap);
                        }
                    }
                });
    }


    private boolean isVerify = false;

    /**
     * 获取认证结果查询
     */


    public void startTakePhoto(int type) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                takeType = type;
                if (type == 1) {
                    startActivity(DEFAULT_NAME1);
                }
                if (type == 2) {
                    startActivity(DEFAULT_NAME2);
                } else if (type == 3) {
                    goToTakePhoto();
                }
            }

            @Override
            public void onReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    private void startActivity(String paramString) {
        Intent localIntent = new Intent(this, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", paramString);
        localIntent.putExtra("type", "idcard");
        startActivityForResult(localIntent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
                try {

                    if (takeType == 1) {
                        if (IdCardBitmap.bitmap != null) {
                            getIdentity(0);
                        }
                    } else if (takeType == 2) {

                        if (IdCardBitmap.bitmap != null) {
                            getIdentity(1);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (requestCode == CAMERA_REQUEST_CODE && resultCode == -1) {
            if (mTempCameraFile.exists()) {
                try {
//                    fragmentOne.setPhoto(takeType, ImageUtil.getimage(mTempCameraFile.getAbsolutePath(), 750, 500, 250));
                    Bitmap bitmap = ImageUtil.getBitmapFromUrl(mTempCameraFile.getAbsolutePath(), 750, 500);
                    getUploadImage(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }
    }

    private String name;
    private String idno;
    private String face;

    public void setIdcardInfo(String name, String idno) {
        this.name = name;
        this.idno = idno;
    }

//    public void setFaceInfo(String face) {
//        this.face = face;
//    }


    private void goToTakePhoto() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (Build.VERSION.SDK_INT >= 23) {
                    Intent cameraIntent;
                    if (Build.VERSION.SDK_INT < 24) {
                        cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempCameraFile()));
                        startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    } else {
                        cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        Uri apkUri = FileProvider.getUriForFile(IdcardIdentityActivity.this, "com.yiwei.jmx.fileprovider", getTempCameraFile());
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, apkUri);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    }
                } else {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempCameraFile()));
                    startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                }
            }

            @Override
            public void onReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private File getTempCameraFile() {
        if (mTempCameraFile == null)
            mTempCameraFile = ImageUtil.getTempMediaFile();
        return mTempCameraFile;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (IdCardBitmap.bitmap != null) {
            IdCardBitmap.bitmap.recycle();
            IdCardBitmap.bitmap = null;
        }

//        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;

    }

    @Override
    public void onBackPressed() {
        selectMenuTipsDilaog.show();
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        selectMenuTipsDilaog.show();
    }

    @OnClick({R.id.btn_wechat, R.id.btn_one_take, R.id.btn_one_retake, R.id.btn_two_take, R.id.btn_two_retake, R.id.btn_one_change, R.id.btn_two_change, R.id.btn_three_take, R.id.btn_three_retake, R.id.btn_submit, R.id.txt_tips})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_wechat:
                Util.startActivity(this, WechatChatActivity.class);
                break;
            case R.id.btn_one_take:
            case R.id.btn_one_retake:
                startTakePhoto(1);
                break;
            case R.id.btn_two_take:
            case R.id.btn_two_retake:
                startTakePhoto(2);
                break;
            case R.id.btn_one_change:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(txtName, 0);
                break;
            case R.id.btn_two_change:
                InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm1.showSoftInput(txtPlace, 0);
                break;
            case R.id.btn_three_take:
            case R.id.btn_three_retake:
                Dialog.showTakePhotoDialog(this, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        startTakePhoto(3);
                    }

                    @Override
                    public void cancel() {

                    }
                });

                break;
            case R.id.btn_submit:
                if (!frontIdentity) {
                    Dialog.showDefaultDialog(this, "提示", "请添加身份证正面", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(1);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                if (!backIdentity) {

                    Dialog.showDefaultDialog(this, "提示", "请添加身份证反面", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(2);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                if (TextUtils.isEmpty(newModel.getHand_image())) {
                    Dialog.showDefaultDialog(this, "提示", "请添加手持身份证", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            startTakePhoto(3);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                if (UI.toString(txtName).length() < 2) {
                    ToastUtil.makeText(this, "姓名请补充完毕");
                    return;
                }
                newModel.setName(UI.toString(txtName));
                sureIdentityDialog.setData(UI.toString(txtIdcardNo), UI.toString(txtName));
                sureIdentityDialog.show();
//                getSubmitidCard(newModel);
                break;
            case R.id.txt_tips:
                Util.startActivity(this, IdcardIdentityFailTipsActivity.class);
                break;
        }
    }
}
